<!-- 检票员端 检票 -->
<template>
  <div class="container">
    <div class="head">
      <div class="scan-wrap">
        <div class="opt-wrap" @click="typeShow = true">
          <div class="text">{{ selectItem.name }}</div>
          <van-icon name="arrow-down" />
        </div>
        <div class="ipt-wrap">
          <input type="text" class="ipt" readonly v-model="scanRes" placeholder="请扫码">
        </div>
        <div class="scan-btn" @click="onScan">
          <i class="iconfont icon-scan"></i>
        </div>
      </div>
    </div>
    <div class="main">
      <div class="content-wrap">
        <div class="title-wrap">
          <div class="title">检票信息</div>
          <div class="btn" @click="onNavTo">
            查看检票记录 <van-icon name="arrow" />
          </div>
        </div>
        <div class="detl-wrap">
          <template v-if="detlData.shuttle_name">
            <div class="field-wrap" v-for="(item, i) in fieldList" :key="i">
              <div class="label">{{ item.label }}</div>
              <div class="val" v-if="item.type === 'text'">{{ detlData[item.key] }}</div>
              <div class="val" v-else-if="item.type === 'img'">
                <img :src="detlData[item.key]" alt="" class="img">
              </div>
              <div class="val" v-else-if="item.type === 'upload'">
                <!-- <van-uploader
                  preview-size="72"
                  :file-list="picList"
                  :before-read="beforeRead"
                  :after-read="afterRead"
                  :show-upload="true"
                  :max-count="picLimit"
                  @delete="deleteFile"
                /> -->
                <van-uploader preview-size="72" :multiple="picLimit > 1" :max-count="picLimit"

                              :file-list="picList"
                              :before-read="beforeRead"
                              :after-read="afterRead"
                />
              </div>
              <div class="val val-select" v-else-if="item.type === 'select'" @click="item.show = true">
                <div class="text">{{ detlData[item.key] }}</div>
                <van-icon name="arrow" />
              </div>
              <m-select v-if="item.type === 'select'" v-model="item.show" :options="item.optionList" @select="(selectItem) => onFieldSelect(selectItem, item.key)"></m-select>
            </div>
            <van-button class="btn" color="#2882FE" @click="onSave">提交</van-button>
          </template>
          <van-empty v-else description="请扫码" />
        </div>
      </div>
    </div>
    <m-select v-model="typeShow" :options="typeOptList" @select="onTypeSelect"></m-select>
  </div>
</template>

<script>
import { Toast, Uploader, Empty, } from 'vant'
import form from '@/components/form/form'
import select from '@/components/select/select'
import { uploadFile,mapGeocoder } from '@/request/api'
import { getWxJssdkConfParams, } from '@/utils/wxJssdkConfigParams'

import {imgCompress,file2Img} from "../../utils/img";
import {getLocation} from "../../utils/wx";
import {crtTimeFtt} from "../../utils/utils";

const http = process.env.NODE_ENV === 'development' ? process.env.VUE_APP_PATH : window.webConfig.webApiBasePath

export default {
  name: '',
  components: {
    'm-form': form,
    'm-select': select,
    [Uploader.name]: Uploader,
    [Empty.name]: Empty,
  },
  computed: {

  },
  data() {
    return {
      typeOptList: [
        { id: '0', name: '去程上车扫码', },
        { id: '1', name: '去程下车扫码', },
        { id: '2', name: '回程上车扫码', },
        { id: '3', name: '回程下车扫码', },
      ],
      selectItem: {
        id: '0',
        name: '去程上车扫码',
      },
      typeShow: false,
      fieldList: [
        { key: 'shuttle_name', label: '班车名称', type: 'text', disabled: true, },
        { key: 'packag_type_name', label: '套票类型', type: 'text', disabled: true, },
        { key: 'ticket_typall_name', label: '票种', type: 'text', disabled: true, },
        { key: 'seat_no', label: '去程座位', type: 'text', disabled: true, },
        { key: 'seat_no_leave', label: '回程座位', type: 'text', disabled: true, },
        { key: 'passengers_name', label: '乘车人姓名', type: 'text', disabled: true, },
        { key: 'pictures_link', label: '照片', type: 'img', disabled: true, },
        { key: 'checkRes', label: '核验结果', type: 'select', disabled: true, optionList: [
          { id: 1, name: '通过', },
          { id: 0, name: '不通过', },
        ], show: false, },
        { key: '', label: '拍照', type: 'upload', disabled: true, },
      ],
      detlData: {
        // shuttle_name: '智城1号',
        // packag_type_name: '往返套票',
        // ticket_typall_name: '月票',
        // seat_no: '4',
        // seat_no_leave: '4',
        // passengers_name: '王小明',
        // pictures_link: 'http://yfgpwebapi.fszyrj.com/SchoolBus/UploadFiles/00443585-09f0-4377-9c5b-669154d800e3_MVIMG_20230607_094800.jpg',
        // checkRes: '',
      },

      picList: [],
      picLimit: 1,

      // resShow: false,
      scanRes: '',
      wx: null,
    }
  },
  watch: {
    picList(newVal, oldVal) {

    },
  },
  created() {
    getWxJssdkConfParams().then(res => {
      this.wx = res
    }, err => {
      console.log('err', err);
    })
    // this.getDetlData()
  },
  methods: {
    /*// 选择文件前
    beforeRead(file) {
      console.log('读取文件前', file);

      return new Promise(resolve => {
        // 文件超出500k压缩
        if(file.size < 512000) resolve(file)
        else imgCompress(file).then(f => resolve(f))
      })
    },
    // 选择图片后操作
    afterRead(e){
      console.log('选择文件后：', e)
      let formData = new FormData()
      formData.append('file', e.file)
      uploadFile(formData).then(res => {
        if(res.errcode !== 0) return
        let { shortName, url, } = res.row[0],
            obj = {
              name: shortName,
              url: http + url,
              id: url,
            }
        if(this.picLimit === 1) {
          this.picList = [obj]
        } else {
          this.picList = [ ...this.picList, obj, ]
        }
      })
    },*/


    beforeRead (file){
      console.log('读取文件前',file);
      return new Promise(async resolve => {
        /*//文件超出500k压缩
        if (file.size < 512000) resolve(file)
        else imgCompress(file).then(f => resolve(f))*/
        let local = '',
          now = new Date(),
          date = crtTimeFtt(now,'YYYY-MM-DD'),
          time = crtTimeFtt(now,'HH:mm');
        await this.getLocation().then(name => local = name);
        let opts = [
          {
            content: local,
            font: '24px serif',
            position: {
              bottom: 20,
              left: 30
            }
          },
          {
            content: '粤A66666',
            font: '24px serif',
            position: {
              bottom: 50,
              left: 30
            }
          },
          {
            content: time,
            font: '36px serif',
            position: {
              bottom: 80,
              left: 30
            }
          },
          {
            content: date,
            font: '26px serif',
            position: {
              bottom: 120,
              left: 30
            }
          },
        ]
        imgCompress(file,opts).then(f => resolve(f));
      })
    },
    afterRead (data) {
      file2Img(data.file).then( f => {
        this.picList = [{
          url: f.src,
          isImage: true
        }]
      })
    },

    getLocation(){
      return new Promise(resolve => {
        getLocation().then(res => {
          let {latitude,longitude} = res;
          if (!latitude || !longitude)return;
          mapGeocoder(
            {
              "key": process.env.NODE_ENV === 'development' ? process.env.VUE_APP_MAPKEY : window.webConfig.webMapKey,
              "location": `${latitude},${longitude}`,
              "get_poi": "",
              "poi_options": "",
              "output": "",
              "callback": ""
            }).then(res =>{
            let {result} = res,
              {city,district} = result.address_component,
              {recommend} = result.formatted_addresses;
            console.log(city);
            console.log(recommend);
            resolve(`${city}·${recommend}`)
          })
        },err => {
          console.log(err);
          resolve('');
        })
      })
    },
    // 删除图片
    deleteFile(e) {
      let index = this.picList.findIndex(item => item.url === e.url)
      this.picList.splice(index, 1)
    },

    onScan() {
      if(!this.wx) return
      this.wx.scanQRCode({
        needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
        scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码，默认二者都有
        success: (res) => {
          let result = res.resultStr // 当needResult 为 1 时，扫码返回的结果
          this.scanRes = result
          // 获取数据
          this.getDetlData()
        }
      })
    },
    onSave() {
      console.log('点击了提交');
      Toast('提交成功')
    },
    onFieldSelect(selectItem, key) {
      this.detlData[key] = selectItem.name
    },
    onTypeSelect(item) {
      this.selectItem = item
    },
    onNavTo() {
      this.$router.push({ name: 'trec', })
    },

    // 假数据
    getDetlData() {
      if(!this.scanRes) return
      Toast.loading({
        duration: 0,
        forbidClick: true,
      })
      let timer = setTimeout(() => {
        Toast.clear()
        clearTimeout(timer)

        this.detlData = {
          shuttle_name: '智城1号',
          packag_type_name: '往返套票',
          ticket_typall_name: '月票',
          seat_no: '4',
          seat_no_leave: '4',
          passengers_name: '王小明',
          pictures_link: 'http://yfgpwebapi.fszyrj.com/SchoolBus/UploadFiles/00443585-09f0-4377-9c5b-669154d800e3_MVIMG_20230607_094800.jpg',
          checkRes: '通过',
        }
      }, 500)
    },
  },
}
</script>

<style scoped lang="less">
.container {
  width: 100%;
  height: calc(100% - 50px);
  box-sizing: border-box;
  overflow: auto;

  >.main {
    height: unset;
  }
}

.container {
  padding: 15px;

  >.head {
    margin-bottom: 20px;

    >.scan-wrap {
      display: flex;
      align-items: center;
      height: 46px;
      padding: 5px 10px;
      border-radius: 8px;
      color: #1989fa;
      background: #fff;

      >.opt-wrap {
        display: flex;
        align-items: center;
        margin-right: 10px;
        padding-right: 10px;
        border-right: 2px dashed #e0e0e0;

        >.text {
          width: 3em;
          margin-right: 4px;
          font-size: 14px;
        }
      }

      >.ipt-wrap {
        flex: 1;
        display: flex;
        height: 100%;

        >.ipt {
          flex: 1;
          width: 0;
          height: 100%;
          font-size: 20px;
          font-weight: bold;
          line-height: 0;

          &::placeholder {
            color: #cccccc;
          }
        }
      }

      >.scan-btn {
        // flex: 1;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;

        &::before {
          content: '';
          height: 33px;
          border-left: 2px dashed #e0e0e0;
        }

        >.iconfont {
          margin-left: 10px;
          font-size: 20px;
        }
      }
    }

  }

  >.main {
    font-size: 14px;

    >.content-wrap {

      >.title-wrap {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;

        >.btn {
          color: #808080;
        }
      }

      >.detl-wrap {
        padding: 15px;
        border-radius: 8px;
        font-size: 15px;
        background: #fff;

        >.field-wrap {
          display: flex;
          margin-bottom: 15px;

          >.label {
            min-width: 6.5em;
            color: #808080;
          }

          >.val {
            flex: 1;

            >.img {
              width: 100%;
            }

            &.val-select {
              display: flex;
              align-items: center;

              >.text {
                flex: 1;
              }
            }
          }
        }

        >.btn {
          width: 100%;
          height: 37px;
          border-radius: 4px;
        }
      }
    }
  }

}
</style>
